package com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.memberrecharge;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.adapter.RechargeAdapter;
import com.zzsy.carosshopprojects.adapter.RegsterMoneyGridAdapter;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.bean.ActivityBean;
import com.zzsy.carosshopprojects.bean.MainCardListBean;
import com.zzsy.carosshopprojects.bean.MemberResultBean;
import com.zzsy.carosshopprojects.bean.RechargeDataBean;
import com.zzsy.carosshopprojects.bean.ResterPostionBeans;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.SoftKeyBoardListener;
import com.zzsy.carosshopprojects.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * 会员充值
 */
public class MemberRechargeFragment extends BaseFragment {
    public static MemberRechargeFragment newInstance(String uuid, MainCardListBean.MyMainCardsBean cardBean) {
        MemberRechargeFragment memberRechargeFragment = new MemberRechargeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("uuid", uuid);
        bundle.putSerializable("cardBean", cardBean);
        memberRechargeFragment.setArguments(bundle);
        return memberRechargeFragment;
    }

    @BindView(R.id.tv_memeber_ye)
    TextView tvMemeberBan;
    @BindView(R.id.tv_member_phone)
    TextView tvMemberPhone; //会员电话号
    @BindView(R.id.tv_oils)
    TextView tvOils;//油品
    //@BindView(R.id.tv_reghter_amounts)
    EditText tvReghterAmount; //充值金额
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;//用户名
    @BindView(R.id.rl_regster_money)
    RecyclerView reghterMoneyRecyclerView; //获取充值金额列表.
    @BindView(R.id.ll_go_sel_coupon)
    LinearLayout llGoSelCoupon;//跳转选择活动事件
    @BindView(R.id.rv_view)
    RecyclerView rvView; //活动优惠券列表展示
    @BindView(R.id.tv_pay)
    TextView tvPay;//点击进行收款
    @BindView(R.id.tv_activity_name)
    TextView tvActivityName;
    @BindView(R.id.tv_show_activity)
    TextView tvShowActivity;
    private String amount;
    private String activityId;
    private String activityPositionId;
    private String receiveAmount = "";
    private String activitySummary;
    private RegsterMoneyGridAdapter regsterMoneyGridAdapter;
    private MemberRechargeMode memberRechargeMode;
    private MemberResultBean memberResultBean;
    private RechargeAdapter rechargeAdapter;
    private ArrayList<ActivityBean> couponList;
    private ArrayList<RechargeDataBean> rechargeDataBeanList;
    private List<ResterPostionBeans> selectRegsterMoneyList;


    @Override
    protected int initLayout() {
        return R.layout.fg_memberrecharge;
    }

    @Override
    protected void initView(View view) {
        initTitle(view, getResources().getString(R.string.MemberRecharge), getActivity());
    }

    @Override
    protected void initData(Context mContext) {
        couponList = new ArrayList<>();
        rechargeDataBeanList = new ArrayList<>();
        selectRegsterMoneyList = new ArrayList<>();
        regsterMoneyGridAdapter = new RegsterMoneyGridAdapter(getContext(), selectRegsterMoneyList, 0);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 4);
        reghterMoneyRecyclerView.setLayoutManager(gridLayoutManager);
        reghterMoneyRecyclerView.setAdapter(regsterMoneyGridAdapter);
        memberRechargeMode = getViewModelProvider().get(MemberRechargeMode.class);
        regsterMoneyGridAdapter.setOnItemClickListener((v, position) -> {
            regsterMoneyGridAdapter.setPostion(position);
            //判断是否可以去收款
            amount = selectRegsterMoneyList.get(position).getAmountStr();
            tvReghterAmount.setText(amount);
            int amount = selectRegsterMoneyList.get(position).getAmount();
            setClear();
            memberRechargeMode.getCoumoserList(getContext(), amount + "", memberResultBean.getMemberId(), "", memberResultBean.getProductId(), "3", "");
        });
        rechargeAdapter = new RechargeAdapter(getContext(), null, 0);
        rvView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        rvView.setAdapter(rechargeAdapter);
    }

    @Override
    protected void loadMethod() {
        setSoftKeyBoardListener();
        getOilsRegsterData();
        getCoumoserList();
        setUUIDMemeberData();
        getUUID();


    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tvReghterAmount = getActivity().findViewById(R.id.tv_reghter_amounts);
        InputFilter[] filters = {
                new CashierInputFilter()
        };
        tvReghterAmount.setFilters(filters);
        tvReghterAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = String.valueOf(s);
                boolean isHave = false;
                int num = 0;
                for (int i = 0; i < selectRegsterMoneyList.size(); i++) {
                    if (String.valueOf(text).equals(selectRegsterMoneyList.get(i).getAmountStr())) {
                        isHave = true;
                        num = i;
                    }
                }
                if (isHave) {
                    regsterMoneyGridAdapter.setPostion(num);
                } else {
                    regsterMoneyGridAdapter.setPostion(-1);
                }

            }
        });
    }

    @OnClick({R.id.tv_pay, R.id.ll_go_sel_coupon})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_pay:
                String amount = tvReghterAmount.getText().toString().trim();
                if (StringUtils.isEmpty(amount)) {
                    ToastUtils.showToast(getContext().getApplicationContext(), "请输入充值金额！");
                    return;
                }

                boolean softShowing = isSoftShowing();
                if (softShowing) {//如果开启
                    ToastUtils.showToast(getContext().getApplicationContext(), "请关闭软键盘进行收款");
                    return;
                }

                /**
                 * 判断是否有网络
                 * */
//                if (ApkInfoUtil.isNetworkConnected(getContext().getApplicationContext())) {
//                    /**
//                     * 如果有网络的时候 进行登录
//                     * */
//                    toPay();
//                } else {
//                    /**
//                     * 判断当前网络
//                     * */
//                    ShowDialogUtils.showDialogs(getActivity(), ComOneBtnDialog.DIALOG_NOT_WIFI, -1);
//                }
                toPay();
                break;
            case R.id.ll_go_sel_coupon: //跳转选择活动界面
                startForResult(CouponListFragment.newInstance(couponList), 101);
                break;

        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == 102) {
            ActivityBean activityBean = (ActivityBean) data.getSerializable("key");
            tvShowActivity.setVisibility(View.GONE);
            activityId = "";
            activityPositionId = "";
            activitySummary = "";
            receiveAmount = "";
            setData(activityBean);
        } else if (requestCode == 101 && resultCode == 103)//不使用活动
        {
            activityId = "";
            activityPositionId = "";
            activitySummary = "";
            receiveAmount = "";

            if (rechargeDataBeanList != null) {
                rechargeDataBeanList.clear();
            }

            llGoSelCoupon.setVisibility(View.VISIBLE);
            rvView.setVisibility(View.GONE);
            tvActivityName.setVisibility(View.GONE);
            tvShowActivity.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取充值档位
     */
    private void getOilsRegsterData() {
        memberRechargeMode.getLiveData().observe(this, resterPostionBeans -> {
            selectRegsterMoneyList = resterPostionBeans;
            regsterMoneyGridAdapter.setListData(selectRegsterMoneyList);
            regsterMoneyGridAdapter.notifyDataSetChanged();
        });
        memberRechargeMode.getOilsRegsterData();
    }

    /**
     * 添加软键盘的监听
     */
    private void setSoftKeyBoardListener() {
        SoftKeyBoardListener softKeyBoardListener = new SoftKeyBoardListener(getActivity());
        softKeyBoardListener.setOnSoftKeyBoardChangeListener(new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {

            }

            @Override
            public void keyBoardHide(int height) {
                amount = tvReghterAmount.getText().toString();
                if (amount.length() > 0) {
                    if ("0".equals(amount)) {
                        ToastUtils.showToast(getContext().getApplicationContext(), "请输入大于0的整数！");
                        showInput(tvReghterAmount);
                    } else {
                        int amounts = Integer.parseInt(amount);
                        setClear();
                        if (memberResultBean != null) {
                            memberRechargeMode.getCoumoserList(getContext(), String.valueOf((amounts * 100)), memberResultBean.getMemberId(), "", memberResultBean.getProductId(), "3", "");
                        } else {
                            ToastUtils.showToast(getContext().getApplicationContext(), "会员信息异常");
                        }
                    }

                } else {
                    //  tvReghterAmount.setHint("自定义充值金额");
                    setClear();
                    llGoSelCoupon.setVisibility(View.GONE);
                    rvView.setVisibility(View.GONE);
                }

            }
        });
    }

    private void setClear() {
        activityId = "";
        activityPositionId = "";
        activitySummary = "";
        receiveAmount = "";

        if (couponList != null) {
            couponList.clear();
        }
        if (rechargeDataBeanList != null) {
            rechargeDataBeanList.clear();
        }

        llGoSelCoupon.setVisibility(View.GONE);
        rvView.setVisibility(View.GONE);
        tvActivityName.setVisibility(View.GONE);
        tvShowActivity.setVisibility(View.GONE);
    }

    /**
     * 获取会员信息
     */
    private void getUUID() {
        String uuid = getArguments().getString("uuid");
        MainCardListBean.MyMainCardsBean cardBean = (MainCardListBean.MyMainCardsBean) getArguments().getSerializable("cardBean");
        if (!StringUtils.isEmpty(uuid)) {
            memberRechargeMode.getUUIDMemeberData(getActivity(), uuid);
        }

        if (cardBean != null) {
            memberRechargeMode.getPhoneMemberDta(getActivity(), cardBean);
        }

    }

    /**
     * 显示会员信息
     */
    private void setUUIDMemeberData() {
        memberRechargeMode.getLiveMrbData().observe(this, memberResultBean -> {
            this.memberResultBean = memberResultBean;
            BigDecimal bigDecimal = ConverterHelper.toBigDecimal(memberResultBean.getRechargeBalance()).divide(ConverterHelper.toBigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            double banalace = bigDecimal.doubleValue();
            String banalaceStr = banalace + "";
            tvMemeberBan.setText("¥ " + StringUtils.setFontSizeSp(getContext(), banalaceStr, banalaceStr.length() - 1, banalaceStr.length(), 14));
            tvMemberPhone.setText(memberResultBean.getPhone());
            tvMemberName.setText(memberResultBean.getRealName());
            if (!StringUtils.isEmpty(memberResultBean.getProductName())) {
                tvOils.setText(memberResultBean.getProductName());
            }
        });

    }

    /**
     * 根据输入充值金额匹配充值档位
     */
    private void getCoumoserList() {
        memberRechargeMode.getLiveAbData().observe(this, activityBeans -> {
            if (activityBeans != null && activityBeans.size() > 0) {
                couponList.clear();
                couponList.addAll(activityBeans);
                setData(activityBeans.get(0));
            } else {
                setClear();
            }

        });
    }


    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public void showInput(final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }


    /**
     * 处理活动数据
     */
    private void setData(ActivityBean data) {
        rechargeDataBeanList.clear();
        activityId = data.getActivityId();
        activityPositionId = data.getActivityPositionId();

        String activityKind = data.getActivityKind();


        if (!StringUtils.isEmpty(activityKind)) {
            if ("3".equals(activityKind)) {
                tvActivityName.setVisibility(View.VISIBLE);
                llGoSelCoupon.setVisibility(View.VISIBLE);
                rvView.setVisibility(View.GONE);
                activitySummary = data.getActivitySummary();
                tvActivityName.setText(activitySummary);
                receiveAmount = data.getActivityValue();
            } else if ("14".equals(activityKind)) {

                llGoSelCoupon.setVisibility(View.VISIBLE);
                rvView.setVisibility(View.VISIBLE);
                tvActivityName.setVisibility(View.GONE);
                List<ActivityBean.CouponDTO> couponList = data.getCouponList();
                List<ActivityBean.ServiceCardDTO> serviceCardDTOList = data.getServiceCardDTOList();

                if (couponList != null && couponList.size() > 0) {
                    for (int i = 0; i < couponList.size(); i++) {
                        rechargeDataBeanList.add(new RechargeDataBean(couponList.get(i).getCouponName(), couponList.get(i).getId(), couponList.get(i).getCreateTime(), "1", couponList.get(i).getPreAmount(), couponList.get(i).getPreKind(), couponList.get(i).getRebate()));
                    }
                }
                if (serviceCardDTOList != null && serviceCardDTOList.size() > 0) {
                    for (int i = 0; i < serviceCardDTOList.size(); i++) {
                        rechargeDataBeanList.add(new RechargeDataBean(serviceCardDTOList.get(i).getName(), serviceCardDTOList.get(i).getId(), serviceCardDTOList.get(i).getCreateTime(), "2", "", couponList.get(i).getPreKind(), couponList.get(i).getRebate()));
                    }
                }
                rechargeAdapter.setListData(rechargeDataBeanList);
                rechargeAdapter.notifyDataSetChanged();
            }

        }

    }

    /**
     * 这个是验证只能输入整数
     */
    public class CashierInputFilter implements InputFilter {
        Pattern mPattern;
        //输入的最大金额
        private static final int MAX_VALUE = 1000000;
        //小数点后的位数
        private static final int POINTER_LENGTH = 0;
        private static final String POINTER = ".";
        private static final String ZERO = "0";

        public CashierInputFilter() {
            mPattern = Pattern.compile("([0-9]|\\.)*");
        }

        /**
         * @param source 新输入的字符串
         * @param start  新输入的字符串起始下标，一般为0
         * @param end    新输入的字符串终点下标，一般为source长度-1
         * @param dest   输入之前文本框内容
         * @param dstart 原内容起始坐标，一般为0
         * @param dend   原内容终点坐标，一般为dest长度-1
         * @return 输入内容
         */
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            String sourceText = source.toString();
            String destText = dest.toString();
            //验证删除等按键
            if (TextUtils.isEmpty(sourceText)) {
                return "";
            }
            Matcher matcher = mPattern.matcher(source);
            //已经输入小数点的情况下，只能输入数字
            if (destText.contains(POINTER)) {
                if (!matcher.matches()) {
                    return "";
                } else {
                    if (POINTER.equals(source)) {  //只能输入一个小数点
                        return "";
                    }
                }
                //验证小数点精度，保证小数点后只能输入2位
                int index = destText.indexOf(POINTER);
                int length = dend - index;
                if (length > POINTER_LENGTH) {
                    return dest.subSequence(dstart, dend);
                }
            } else {
                //没有输入小数点的情况下，只能输入小数点和数字，但首位不能输入小数点和0
                if (!matcher.matches()) {
                    return "";
                } else {
                    if ((POINTER.equals(source)) && TextUtils.isEmpty(destText)) {
                        return "";
                    }
                    //如果首位为“0”，则只能再输“.”
                    if (ZERO.equals(destText)) {
                        if (!POINTER.equals(sourceText)) {
                            return "";
                        }
                    }
                }
            }
            double sumText = 0.0;
            //验证输入金额的大小
            try {
                sumText = Double.parseDouble(destText + sourceText);
            } catch (Exception e) {
                return "";
            }

            if (sumText > MAX_VALUE) {
                return dest.subSequence(dstart, dend);
            }
            return dest.subSequence(dstart, dend) + sourceText;
        }
    }

    private boolean isSoftShowing() {
// 获取当前屏幕内容的高度
        int screenHeight = getActivity().getWindow().getDecorView().getHeight();
// 获取View可见区域的bottom
        Rect rect = new Rect();
// DecorView即为activity的顶级view
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
// 考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
// 选取screenHeight*2/3进行判断
        return screenHeight * 2 / 3 > rect.bottom;
    }

    /**
     * 跳转页面去支付
     */
    private void toPay() {
        if (memberResultBean == null) {
            ToastUtils.showToast(getContext().getApplicationContext(), "数据异常！");
            return;
        }
        startWithPop(RechargePayTwoFragment.newInstance(amount, memberResultBean.getMemberId(), memberResultBean.getProductId(), activityId, activityPositionId, memberResultBean.getMemberCardId(), memberResultBean.getPhone(), receiveAmount, activitySummary, rechargeDataBeanList));
    }


}
